package org.example.designmodel.forkjoin;

import java.util.concurrent.RecursiveTask;

public class AccumulateTask extends RecursiveTask<Integer> {

    private final static int THRESHOLD = 2;

    private int start;

    private int end;

    public AccumulateTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        boolean can = (end - start) <= THRESHOLD;
        if (can) {
            int sum = 0;
            System.out.println("最小化任务：" + start + "-" + end);
            for (int i = start; i <= end; i++) {
                sum = sum + i;
            }
            return sum;
        } else {
            // 分而治之
            int mid = (start + end) / 2;
            System.out.println("分任务1：" + start + "-" + mid);
            AccumulateTask task1 = new AccumulateTask(start, mid);
            System.out.println("分任务2：" + (mid + 1) + "-" + end);
            AccumulateTask task2 = new AccumulateTask(mid + 1, end);
            // 子任务提交
            task1.fork();
            task2.fork();

            // 获取任务的返回结果
            int lresult = task1.join();
            int rresult = task2.join();
            return lresult + rresult;
        }
    }
}
